'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { useUploadUpdate } from '@/api/uploads'
import { toast } from 'sonner'
import { getRouteApi, useRouter } from '@tanstack/react-router'
import { type Upload } from '../data/schema'

interface Props {
  open: boolean
  onOpenChange: (open: boolean) => void
  currentRow: Upload | null
}

export function UploadsEditDialog({ open, onOpenChange, currentRow }: Props) {
  const router = useRouter()
  const routeApi = getRouteApi('/_authenticated/uploads/')
  const { uploadDict } = routeApi.useLoaderData()
  const [category, setCategory] = useState('')
  const uploadUpdate = useUploadUpdate()

  useEffect(() => {
    if (currentRow) {
      setCategory(currentRow.category || '')
    }
  }, [currentRow])

  const handleUpdate = () => {
    if (!currentRow) return

    uploadUpdate.mutate(
      {
        id: currentRow.id,
        category,
      },
      {
        onSuccess: () => {
          toast.success('Upload updated successfully!')
          onOpenChange(false)
          router.invalidate()
        },
      }
    )
  }

  const handleOpenChange = (isOpen: boolean) => {
    if (!isOpen) {
      // Reset form when closing
      if (currentRow) {
        setCategory(currentRow.category || '')
      }
    }
    onOpenChange(isOpen)
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className='sm:max-w-md'>
        <DialogHeader>
          <DialogTitle>Edit Upload</DialogTitle>
          <DialogDescription>
            Update the upload details here. Click save when you&apos;re done.
          </DialogDescription>
        </DialogHeader>
        <div className='grid gap-4 py-4'>

          <div className='grid grid-cols-4 items-center gap-4'>
            <Label htmlFor='category-select' className='text-right'>
              Category
            </Label>
            <Select onValueChange={setCategory} value={category}>
              <SelectTrigger className='col-span-3'>
                <SelectValue placeholder="Select a category" />
              </SelectTrigger>
              <SelectContent>
                {uploadDict.map((item) => (
                  <SelectItem key={item.value} value={item.value}>
                    {item.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
        <DialogFooter>
          <Button
            type='button'
            onClick={handleUpdate}
            disabled={uploadUpdate.isPending}
          >
            {uploadUpdate.isPending ? 'Saving...' : 'Save'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}